import type { DesktopCapturerSource } from 'electron';
import { makeAutoObservable } from 'mobx';
type RecordType = 'screen' | 'window' | 'camera' | 'voice';
class Store {
  static _instance: any;
  constructor() {
    makeAutoObservable(this);
  }

  windowList: DesktopCapturerSource[] = [];
  fullScreen: DesktopCapturerSource | null = null;
  currentRecorder: MediaRecorder | null = null;
  currentWindow: DesktopCapturerSource | null = null;
  startTime = 0;
  recordTime = 0; // 录制时长
  pauseTime = 0; // 暂停时间
  endTime = 0;
  timer: any = undefined; // 定时器
  recordType: RecordType = 'screen';
  minWindowRecorder = localStorage.getItem('minWindowRecorder') === 'true';

  getScreenList = () => {
    window.api.getScreenSource((data: DesktopCapturerSource[]) => {
      this.windowList = data.filter((win) => !win.id.includes('screen'));
      this.fullScreen = data.filter((win) => win.id.includes('screen'))[0];
      this.currentWindow = this.fullScreen; // 默认全屏录制
      this.createRecorder();
    });
  };

  // TODO: 创建录制器
  createRecorder = async () => {
    const videoConfig: Record<string, any> = {};
    if (this.recordType === 'camera') {
      videoConfig.facingMode = 'user';
    }
    // 获取视频流
    const stream = await navigator.mediaDevices.getUserMedia({
      audio: false,
      video: {
        // facingMode: 'user',ß
        mandatory: {
          chromeMediaSource: 'desktop',
          chromeMediaSourceId: this.currentWindow?.id || 0,
          minWidth: 1920,
          maxWidth: 1920,
          minHeight: 1080,
          maxHeight: 1080
        }
      }
    } as any);
    const audioTracks = await navigator.mediaDevices
      .getUserMedia({ audio: true, video: false })
      .then((mediaStream) => {
        window.console.log(mediaStream.getAudioTracks(), '视频流');
        return mediaStream.getAudioTracks()[0];
      });
    stream.addTrack(audioTracks);
    const recorder = new MediaRecorder(stream);
    this.currentRecorder = recorder;
    // 如果 start 没设置 timeslice，ondataavailable 在 stop 时会触发
    recorder.ondataavailable = (event: BlobEvent) => {
      const blob = new Blob([event.data], {
        type: 'video/mp4'
      });
      const reader = new FileReader();
      reader.onload = () => {
        console.log('保存视频');
        window.api.downloadFile(reader.result, localStorage.getItem('videoCacheDir') || '');
      };
      reader.readAsBinaryString(blob);
    };

    recorder.onerror = (err) => {
      console.error(err);
    };
  };

  startRecord = async () => {
    this.recordTime = 0;
    this.timer = setInterval(() => {
      this.recordTime = this.recordTime + 1000;
    }, 1000);
    console.log(this.currentRecorder);
    this.currentRecorder?.start();
  };

  // 停止录制
  stopRecord = () => {
    this.currentRecorder?.state !== 'inactive' && this.currentRecorder?.stop();
    this.timer && clearInterval(this.timer);
    this.timer = null;
  };

  // 暂停录制
  pauseRecord = (continueRecord = false) => {
    console.log(continueRecord);
    if (continueRecord) {
      // 继续录制
      this.timer = setInterval(() => {
        this.recordTime = this.recordTime + 1000;
      }, 1000);
    } else {
      clearInterval(this.timer);
      this.timer = null;
    }
    this.currentRecorder?.pause();
  };

  setStore = (
    data: Partial<{
      currentWindow: DesktopCapturerSource;
      recordTime: number;
      pauseTime: number;
      startTime: number;
      endTime: number;
      minWindowRecorder: boolean;
    }>
  ) => {
    Object.keys(data).forEach((key) => {
      localStorage.setItem(key, JSON.stringify(data[key]));
      this[key] = data[key];
    });
  };
}

export default new Store();
